<template>
  <div class="login-log">
    <a-card :bordered="false" class="search-form">
      <a-form layout="inline" :model="queryParams" @finish="handleSearch">
        <a-row :gutter="16">
          <a-col :span="6">
            <a-form-item :label="t('loginLog.username')" name="username">
              <a-input
                v-model:value="queryParams.username"
                :placeholder="t('loginLog.placeholder.username')"
                allow-clear
              />
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item :label="t('loginLog.ip')" name="ip">
              <a-input
                v-model:value="queryParams.ip"
                :placeholder="t('loginLog.placeholder.ip')"
                allow-clear
              />
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item :label="t('loginLog.location')" name="location">
              <a-input
                v-model:value="queryParams.location"
                :placeholder="t('loginLog.placeholder.location')"
                allow-clear
              />
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item :label="t('loginLog.status.label')" name="status">
              <a-select
                v-model:value="queryParams.status"
                :placeholder="t('loginLog.placeholder.status')"
                allow-clear
                style="width: 100%"
              >
                <a-select-option :value="1">{{ t('loginLog.status.success') }}</a-select-option>
                <a-select-option :value="0">{{ t('loginLog.status.failed') }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item :label="t('loginLog.browser')" name="browser">
              <a-input
                v-model:value="queryParams.browser"
                :placeholder="t('loginLog.placeholder.browser')"
                allow-clear
              />
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item :label="t('loginLog.os')" name="os">
              <a-input
                v-model:value="queryParams.os"
                :placeholder="t('loginLog.placeholder.os')"
                allow-clear
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item :label="t('loginLog.loginTime')" name="loginTime">
              <a-range-picker
                v-model:value="dateRange"
                :show-time="{ format: 'HH:mm:ss' }"
                format="YYYY-MM-DD HH:mm:ss"
                :placeholder="[t('loginLog.time.start'), t('loginLog.time.end')]"
                style="width: 100%"
                @change="handleDateRangeChange"
              />
            </a-form-item>
          </a-col>
          <a-col :span="24" style="text-align: right">
            <a-space>
              <a-button type="primary" html-type="submit">
                <template #icon><search-outlined /></template>
                {{ t('common.search') }}
              </a-button>
              <a-button @click="handleReset">
                <template #icon><redo-outlined /></template>
                {{ t('common.reset') }}
              </a-button>
              <a-button type="primary" danger @click="handleClean">
                <template #icon><delete-outlined /></template>
                {{ t('loginLog.clean') }}
              </a-button>
            </a-space>
          </a-col>
        </a-row>
      </a-form>
    </a-card>

    <!-- 数据表格 -->
    <a-card :bordered="false" class="table-card">
      <a-table
        :columns="columns"
        :data-source="loginLogList"
        :loading="loading"
        :pagination="pagination"
        @change="handleTableChange"
        :scroll="{ x: 1200 }"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'status'">
            <a-tag :color="record.status === 1 ? 'success' : 'error'">
              {{ record.status === 1 ? t('loginLog.status.success') : t('loginLog.status.failed') }}
            </a-tag>
          </template>
          <template v-if="column.key === 'loginTime'">
            {{ formatDateTime(record.loginTime) }}
          </template>
        </template>
      </a-table>
    </a-card>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { message, Modal } from 'ant-design-vue'
import type { TablePaginationConfig } from 'ant-design-vue'
import { useI18n } from 'vue-i18n'
import { SearchOutlined, RedoOutlined, DeleteOutlined } from '@ant-design/icons-vue'
import type { LoginLogInfo, LoginLogQuery } from '@/types/login-log.type'
import { getLoginLogList, cleanLoginLog } from '@/api/login-log'
import dayjs from 'dayjs'

const { t } = useI18n()

// 查询参数
const queryParams = reactive<LoginLogQuery>({
  username: '',
  ip: '',
  location: '',
  browser: '',
  os: '',
  status: undefined,
  startTime: '',
  endTime: '',
  current: 1,
  size: 10
})

// 日期范围
const dateRange = ref<[dayjs.Dayjs, dayjs.Dayjs] | null>(null)

// 表格列定义
const columns = [
  {
    title: t('loginLog.username'),
    dataIndex: 'username',
    key: 'username',
    width: 120,
    fixed: 'left'
  },
  {
    title: t('loginLog.ip'),
    dataIndex: 'ip',
    key: 'ip',
    width: 120
  },
  {
    title: t('loginLog.browser'),
    dataIndex: 'browser',
    key: 'browser',
    width: 120
  },
  {
    title: t('loginLog.os'),
    dataIndex: 'os',
    key: 'os',
    width: 120
  },
  {
    title: t('loginLog.status.label'),
    dataIndex: 'status',
    key: 'status',
    width: 100
  },
  {
    title: t('loginLog.loginTime'),
    dataIndex: 'loginTime',
    key: 'loginTime',
    width: 180,
    fixed: 'right'
  }
]

// 登录日志列表数据
const loginLogList = ref<LoginLogInfo[]>([])
const loading = ref(false)
const pagination = reactive<TablePaginationConfig>({
  total: 0,
  current: 1,
  pageSize: 10,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total) => t('common.total', { total })
})

// 格式化日期时间
const formatDateTime = (dateTime: string) => {
  return dayjs(dateTime).format('YYYY-MM-DD HH:mm:ss')
}

// 获取登录日志列表
const fetchLoginLogList = async () => {
  loading.value = true
  try {
    const res = await getLoginLogList(queryParams)
    loginLogList.value = res.records
    pagination.total = res.total
  } catch (error: any) {
    message.error(error.message || t('common.failed'))
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  queryParams.current = 1
  fetchLoginLogList()
}

// 重置
const handleReset = () => {
  queryParams.username = ''
  queryParams.ip = ''
  queryParams.location = ''
  queryParams.browser = ''
  queryParams.os = ''
  queryParams.status = undefined
  queryParams.startTime = ''
  queryParams.endTime = ''
  dateRange.value = null
  queryParams.current = 1
  fetchLoginLogList()
}

// 日期范围变化
const handleDateRangeChange = (dates: [dayjs.Dayjs, dayjs.Dayjs] | null) => {
  if (dates) {
    queryParams.startTime = dates[0].format('YYYY-MM-DD HH:mm:ss')
    queryParams.endTime = dates[1].format('YYYY-MM-DD HH:mm:ss')
  } else {
    queryParams.startTime = ''
    queryParams.endTime = ''
  }
}

// 表格变化
const handleTableChange = (pag: TablePaginationConfig) => {
  pagination.current = pag.current || 1
  pagination.pageSize = pag.pageSize || 10
  queryParams.current = pagination.current
  queryParams.size = pagination.pageSize
  fetchLoginLogList()
}

// 清空日志
const handleClean = () => {
  Modal.confirm({
    title: t('loginLog.clean'),
    content: t('loginLog.cleanConfirmContent'),
    okText: t('common.confirm'),
    cancelText: t('common.cancel'),
    onOk: async () => {
      try {
        await cleanLoginLog()
        message.success(t('loginLog.cleanSuccess'))
        fetchLoginLogList()
      } catch (error) {
        console.error('Failed to clean login log:', error)
      }
    }
  })
}

onMounted(() => {
  fetchLoginLogList()
})
</script>

<style lang="less" scoped>
.login-log {
  .search-form {
    margin-bottom: 16px;
    :deep(.ant-form-item) {
      margin-bottom: 16px;
    }
  }

  .table-card {
    :deep(.ant-card-body) {
      padding: 0;
    }
  }
}
</style> 